package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"store-master/cache"
	"store-master/models"
	"store-master/pkg"
	"time"
)

type UserController struct {
	beego.Controller
}

func (u *UserController) Login() {

	username := u.GetString("username")
	password := u.GetString("password")
	if username == "" || password == "" {
		u.Data["json"] = Res{
			Code: 0,
			Msg:  "用户名或密码为空",
		}
		u.ServeJSON()
		return
	}
	userLogin := "user_login" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, userLogin).Int()
	if errCount > 3 {
		u.Data["json"] = Res{
			Code: 0,
			Msg:  "密码错误3次",
		}
		u.ServeJSON()
		return
	}
	var user models.User
	err := models.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		u.Data["json"] = Res{
			Code: 0,
			Msg:  "用户不存在",
		}
		u.ServeJSON()
		return
	}
	if user.Password != pkg.Md5Str(password) {
		cache.Rdb.Incr(cache.Ctx, userLogin)
		if errCount > 2 {
			cache.Rdb.Set(cache.Ctx, userLogin, 3, time.Hour*2)
			u.Data["json"] = Res{
				Code: 0,
				Msg:  "密码错误3次,封禁2小时",
			}
			u.ServeJSON()
			return
		}
		u.Data["json"] = Res{
			Code: 0,
			Msg:  "密码错误",
		}
		u.ServeJSON()
		return
	}
	u.Data["json"] = Res{
		Code: 200,
		Msg:  "登录成功",
	}
	u.ServeJSON()
	return
}
